package org.example.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import org.example.config.R;
import org.example.domain.UserDept;
import org.example.service.UserDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("department")
public class UserDeptController {
    @Autowired
    UserDeptService userDeptService;

    @RequestMapping("list")
    public R list(@RequestBody UserDept userDept){
        List<UserDept> lists = userDeptService.lists(userDept);
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
// 自定义属性名 都有默认值的


//转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> treeNodes = TreeUtil.<UserDept, String>build(lists, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId()+"");
                    tree.setParentId(treeNode.getSort()+"");
                    tree.setName(treeNode.getName());
                    // 扩展属性 ...
                    tree.putExtra("cperson", treeNode.getCperson());
                    tree.putExtra("tel", treeNode.getTel());
                    tree.putExtra("email", treeNode.getEmail());
                    tree.putExtra("status", treeNode.getStatus());
                    tree.putExtra("superiors", treeNode.getSuperiors());
                });


        return R.successed(treeNodes);

    }

    @RequestMapping("del")
    public R del(Integer id){
        UserDept id1 = userDeptService.getId(id);
        if(id1==null){
            return R.failed("该数据不存在");
        }

        boolean b = userDeptService.delId(id);
        return R.successed(b);
    }



    @RequestMapping("update")
    public R update(@RequestBody UserDept userDept){
        UserDept id = userDeptService.getId(userDept.getId());
        if(id!=null){
            boolean b = userDeptService.updateSec(userDept);
            return R.successed(b);
        }
        return R.failed("该数据不存在");
    }


    @RequestMapping("addSec")
    public R addSec(@RequestBody UserDept userDept){
        boolean b = userDeptService.addSec(userDept);
        return R.successed(b);
    }

    @RequestMapping("getDeptName")
    public List<UserDept> getDeptName(){
        List<UserDept> list=userDeptService.getDeptName();
        return list;
    }

}
